from PyQt4.QtGui import *
from PyQt4.QtCore import *

from ui.models import NIModel, SelectionModel, DataItem
from core import cmds
from core.base import ParentChanged, NewComponentInst

class DBWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        
        self.list_view = QTreeView(self)
        self.list_view.setModel(NIModel())
        self.list_view.setSelectionModel(SelectionModel(self.list_view.model()))
        self.list_view.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.list_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_view.setAlternatingRowColors(True)
        
        self.list_view.setDragEnabled(True)
        self.list_view.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_view.setAcceptDrops(True)
        self.list_view.setDropIndicatorShown(True)
        
        hbox = QHBoxLayout()
        hbox.addWidget(self.list_view)
        self.setLayout(hbox)
        
        
class DBView(ni.View):
    widget = DBWidget
    
    def setup_widget(self, widget):
        widget.connect(widget.list_view, SIGNAL("customContextMenuRequested(const QPoint&)"), 
                       lambda p, widget=widget: self.on_context_menu(p,widget))
        ParentChanged.connect(self.on_parent_change)
        NewComponentInst.connect(self.on_new_component)
        
    def on_new_component(self, comp, *args):
        for widget in self.widgets:
            parent = widget.list_view.model().invisibleRootItem()
            qitem = DataItem(comp)
            parent.setChild(parent.rowCount(), 0, qitem)
            
    
    def on_parent_change(self, node):
        for widget in self.widgets:
            model = widget.list_view.model()
            model.move_item(model.item_from_data(node), model.item_from_data(node.parent) )
    
    def update_widget(self, widget):
        widget.list_view.model().clear()
        root_nodes = cmds.root_nodes()
        print 'ROOT NODES', root_nodes
        parent = widget.list_view.model().invisibleRootItem()
        self._add_nodes(root_nodes, parent)
        #widget.list_view.model().set_data(root_nodes)
        
    def _add_nodes(self, nodes, parent):
        for node in nodes:
            qitem = DataItem(node)
            parent.setChild(parent.rowCount(), 0, qitem)
            self._add_nodes(node.children, qitem)
    
    def on_context_menu(self, point, widget):
        print 'CONTEXT'
        obj = widget.list_view.model().itemFromIndex(widget.list_view.currentIndex()).data_obj
        menu = cmds.action_menu(obj, widget)
        if menu is None: return
        menu.popup(QCursor.pos()) 
    
    